package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmUserDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.LoginMapper;
import com.heima.wemedia.service.LoginService;
import io.seata.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
@Slf4j
public class LoginServiceImpl extends ServiceImpl<LoginMapper, WmUser>implements LoginService {

    /*
    * todo 自媒体用户登录
    *  */

    @Override
    public ResponseResult login(WmUserDTO wmUserDTO) {
        //TODO 1 检查参数

        if (StringUtils.isBlank(wmUserDTO.getName())||StringUtils.isBlank(wmUserDTO.getPassword())){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"用户名或密码不能为空！！");
        }
        //TODO 查询自媒体用户
        LambdaQueryWrapper<WmUser> lambdaQuery = Wrappers.lambdaQuery();
        LambdaQueryWrapper<WmUser> eq = lambdaQuery.eq(WmUser::getName, wmUserDTO.getName());
        WmUser wmUser = getOne(eq);
        if (wmUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名不存在");
        }
        //TODO 用户状态判断
        if (wmUser.getStatus().intValue()!=9){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"用户状态异常，请联系管理员处理");
        }
        //todo 获取用户输入密码进行MD5加盐加密
        String pwd = DigestUtils.md5DigestAsHex((wmUserDTO.getPassword() + wmUser.getSalt()).getBytes());
        //todo 密码校验
        if (!wmUser.getPassword().equals(pwd)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户密码错误");
        }
        //TODO 返回结果
        HashMap<String, Object> map = new HashMap<>();
        //todo 根据登录用户id生成token
        map.put("token", AppJwtUtil.getToken(Long.valueOf(wmUser.getId())));
        //todo 获取vo对象，用于将pojos实体类的属性转为vo，作用：1、安全 2、提高效率
        WmUserVO wmUserVO = new WmUserVO();
        BeanUtils.copyProperties(wmUser,wmUserVO);
        map.put("user",wmUserVO);
        return ResponseResult.okResult(map);
    }
}
